package com.project.petLossSystem.util;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.springframework.util.ObjectUtils;

import java.util.Collections;

/**
 * opencv直方图
 */
public class ColorHistogramUtil {
    /**
     * 获取指定区域的颜色直方图
     */
    public static Mat calculateColorHistogram(String imagePath, Rect rect) {
        Mat image = Imgcodecs.imread(imagePath);
        if (!ObjectUtils.isEmpty(rect)) {
            image = new Mat(image, rect);
        }
        // 转换图像为HSV色彩空间
        Mat hsvImage = new Mat();
        Imgproc.cvtColor(image, hsvImage, Imgproc.COLOR_BGR2HSV);
        // 计算直方图
        Mat hist = new Mat();
        Imgproc.calcHist(Collections.singletonList(hsvImage), new MatOfInt(0), new Mat(), hist, new MatOfInt(256), new MatOfFloat(0f, 256f));
        // 归一化直方图
        Core.normalize(hist, hist, 0, 1, Core.NORM_MINMAX);
        return hist;
    }

    /**
     * Mat转String
     */
    public static String matToString(Mat mat) {
        float[] data = new float[256]; //计算了
        mat.get(0, 0, data);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length - 1; i++) {
            sb.append(data[i]).append(",");
        }
        sb.append(data[data.length - 1]);
        return sb.toString();
    }

    /**
     * String转Mat
     */
    public static Mat stringToMat(String s) {
        String[] arr = s.split(",");
        float[] data = new float[arr.length];
        for (int i = 0; i < data.length; i++) {
            data[i] = Float.parseFloat(arr[i]);
        }
        Mat mat = new Mat(256, 1, 5); // 计算了
        mat.put(0, 0, data);
        return mat;
    }

    /**
     * 判断相似
     */
    public static boolean compareHist(Mat hist1, Mat hist2){
        return Imgproc.compareHist(hist1, hist2, Imgproc.CV_COMP_CORREL) > 0.5; // 50% 降点
    }
}
